package com.xl.bigdata.es.index;

import com.xl.bigdata.es.xpack.ESXpackRestHighLevelClient;
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;

/**
 * @ClassName RefreshAPI
 * @Description TODO 手动刷新索引，保证数据可搜索
 * 将buffer的索引数据（不可见）写入segment里面，从新打开segment，索引可搜索
 * 数据存放到文件缓存中，并未写入磁盘，等待reflush后，写入磁盘并清空translog
 * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.15/java-rest-high-refresh.html#java-rest-high-refresh-async
 * @Author xl.gao
 * @Date 2022/1/7 18:20
 * @Version
 */
public class RefreshAPI {

    public static boolean refreshAPI(RestHighLevelClient client, String index){

        RefreshRequest refreshRequest = new RefreshRequest(index);

        try {
            RefreshResponse refreshResponse = client.indices().refresh(refreshRequest, RequestOptions.DEFAULT);

            int totalShards = refreshResponse.getTotalShards();
            int successfulShards = refreshResponse.getSuccessfulShards();
            if(totalShards == successfulShards){
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }

    public static void main(String[] args) {


        RestHighLevelClient restHighLevelClient = ESXpackRestHighLevelClient.getRestHighLevelClient();

        boolean address_base = refreshAPI(restHighLevelClient, "address_base");

        if(address_base){
            System.out.println("OK");
        } else {
            System.out.println("NG");
        }

        ESXpackRestHighLevelClient.closeRestHighLevelClient();
    }
}
